<!--
  -    Copyright (c) 2018-2025, bfcloud All rights reserved.
  -
  - Redistribution and use in source and binary forms, with or without
  - modification, are permitted provided that the following conditions are met:
  -
  - Redistributions of source code must retain the above copyright notice,
  - this list of conditions and the following disclaimer.
  - Redistributions in binary form must reproduce the above copyright
  - notice, this list of conditions and the following disclaimer in the
  - documentation and/or other materials provided with the distribution.
  - Neither the name of the pig4cloud.com developer nor the names of its
  - contributors may be used to endorse or promote products derived from
  - this software without specific prior written permission.
  - Author: bfcloud
  -->

<template>
  <div class="user">
    <basic-container>
      <el-row :gutter="20">
        <el-col :xs="24" :sm="24" :md="5">
          <div class="user__tree boxsty">
            <avue-tree
              :option="treeOption"
              :data="treeData"
              @node-click="nodeClick"
            >
              <span class="el-tree-node__label" slot-scope="{ node, data }">
                <el-tooltip class="item" effect="dark" content="无数据权限" placement="right-start" v-if="data.isLock">
                  <span>{{ node.label }} <i class="el-icon-lock"></i></span>
                </el-tooltip>
                <span v-if="!data.isLock">{{ node.label }}</span>
              </span>
            </avue-tree>
          </div>
        </el-col>
        <el-col :xs="24" :sm="24" :md="19">
          <div class="user__main boxsty">
            <div class="tabletext">用户管理</div>
            <avue-crud
              ref="crud"
              :option="option"
              v-model="form"
              :page.sync="page"
              :table-loading="listLoading"
              :before-open="handleOpenBefore"
              :data="list"
              @on-load="getList"
              @search-change="searchChange"
              @refresh-change="refreshChange"
              @size-change="sizeChange"
              @current-change="currentChange"
              @row-update="update"
              @row-save="create"
            >
              <template slot="ryZjbmSearch" slot-scope="scope">
                <avue-select
                  v-model="zdySearchForm.ryZjbm"
                  :dic="userZjOptions"
                  :props="userZjProps"
                  placeholder="请选择职级"
                />
              </template>
              <template slot="menuLeft">
                <el-button
                  v-if="sys_user_add"
                  class="filter-item"
                  type="primary"
                  size="small"
                  icon="el-icon-edit"
                  @click="$refs.crud.rowAdd()"
                  >添加
                </el-button>
              </template>
              <template slot="username" slot-scope="scope">
                <span>{{ scope.row.username }}</span>
              </template>
              <template slot="role" slot-scope="scope">
                <span v-for="(role, index) in scope.row.roleList" :key="index">
                  <el-tag>{{ role.roleName }} </el-tag>&nbsp;&nbsp;
                </span>
              </template>
              <template slot="ryZw" slot-scope="scope">
                <span
                  v-for="(zw, index) in getArray(scope.row.ryZw, '、')"
                  :key="index"
                >
                  <el-tag>{{ zw }} </el-tag>&nbsp;&nbsp;
                </span>
              </template>
              <template slot="deptId" slot-scope="scope">
                {{ scope.row.deptName }}
              </template>
              <template slot="lockFlag" slot-scope="scope">
                <el-tag>{{ scope.label }}</el-tag>
              </template>
              <template style="width: 200px" slot="menu" slot-scope="scope">
                <!--                <el-button v-if="sys_user_edit" type="primary" plain @click="editHead(scope.row.userId)">编辑头像-->
                <!--                </el-button>-->
                <el-button
                  v-if="sys_user_edit"
                  type="primary"
                  plain
                  @click="handleUpdate(scope.row, scope.index)"
                  >编辑
                </el-button>
                <el-button
                  v-if="sys_user_del"
                  type="danger"
                  plain
                  @click="deletes(scope.row, scope.index)"
                  >删除
                </el-button>
              </template>
              <template slot="deptIdForm" slot-scope="scope">
                <avue-input-tree
                  v-model="form.deptId"
                  :node-click="getNodeData"
                  :dic="treeDeptData"
                  :props="defaultProps"
                  placeholder="请选择所属部门"
                />
              </template>
              <template slot="orgaIdForm" slot-scope="scope">
                <avue-input-tree
                  v-model="form.orgaId"
                  :node-click="getNodeData"
                  :dic="treeDeptData"
                  :props="defaultProps"
                  placeholder="请选择所属单位"
                />
              </template>

              <template slot="roleForm" slot-scope="scope">
                <avue-select
                  v-model="role"
                  :dic="rolesOptions"
                  :props="roleProps"
                  multiple
                  placeholder="请选择角色"
                />
              </template>
              <template slot="ryZjbmForm" slot-scope="scope">
                <avue-select
                  v-model="form.ryZjbm"
                  :dic="userZjOptions"
                  :props="userZjProps"
                  placeholder="请选择职级"
                />
              </template>
              <template slot="avatarForm" slot-scope="scope">
                <!--                <avue-img v-model="form.avatar"></avue-img>-->
                <el-upload
                  accept=".png,.jpg"
                  :headers="headers"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess"
                  class="avatar-uploader"
                  action="/admin/sys-file/upload"
                >
                  <img
                    v-if="form.avatar"
                    id="avatar"
                    :src="form.avatar"
                    class="avatar"
                  />
                  <i v-else class="el-icon-plus avatar-uploader-icon" />
                </el-upload>
              </template>
              <template slot="ryQmtpForm" slot-scope="scope">
                <el-upload
                  accept=".png,.jpg"
                  :headers="headers"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccessQm"
                  action="/admin/sys-file/upload"
                  style="width: 100%"
                >
                  <img
                    v-if="form.ryQmtp"
                    id="ryQmtp"
                    :src="form.ryQmtp"
                    style="width: 100%; height: 100px"
                  />
                  <el-button v-else size="small" type="primary"
                    >点击上传</el-button
                  >
                </el-upload>
              </template>
            </avue-crud>
          </div>
        </el-col>
      </el-row>
      <headForm ref="headForm"></headForm>
    </basic-container>
  </div>
</template>

<script>
import { addObj, delObj, fetchList, putObj } from "@/api/admin/user";
import { deptRoleList } from "@/api/admin/role";
import { fetchTree, getTreeList } from "@/api/admin/dept";
import { tableOption } from "@/const/crud/admin/user";
import { remote as remoteDict } from "@/api/admin/dict";
import { mapGetters, mapState } from "vuex";
import headForm from "./head-form";
import store from "@/store";
import { getStore, setStore } from "@/util/store";

export default {
  name: "SysUser",
  components: {
    headForm,
  },
  data() {
    return {
      //图片
      // headers: {
      //   Authorization: "Bearer " + store.getters.access_token,
      //   // ,
      //   // 'TENANT-ID':getStore({ name: 'tenantId' }),
      // },
      headers: { //by my 221213
          'TENANT-ID': getStore({ name: "tenantId" })
              ? getStore({ name: "tenantId" })
              : "1",
          Authorization: "Bearer " + store.getters.access_token,
      },
      searchForm: {},
      zdySearchForm: {},
      treeOption: {
        nodeKey: "id",
        addBtn: false,
        menu: false,
        props: {
          label: "name",
          value: "id",
        },
      },
      treeData: [],
      treeListData: [],
      option: tableOption,
      treeDeptData: [],
      checkedKeys: [],
      roleProps: {
        label: "roleName",
        value: "roleId",
      },
      defaultProps: {
        label: "name",
        value: "id",
      },
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20, // 每页显示多少条,
        isAsc: false, // 是否倒序
      },
      list: [],
      listLoading: true,
      role: [],
      form: {},
      rolesOptions: [],
      ryZjbm: "",
      userZjOptions: [],
      userZjProps: {
        label: "label",
        value: "value",
      },
    };
  },
  computed: {
    ...mapGetters(["permissions"]),
    ...mapState({
      userInfo: (state) => state.user.userInfo,
    }),
  },
  watch: {
    "form.ryZjbm": {
      handler(val) {
        if (val != "" && val != undefined && val != null) {
          this.userZjOptions.forEach((r) => {
            if (r.value == val) {
              this.form.ryZjmc = r.label;
            }
          });
        } else {
          this.form.ryZjmc = "";
        }
      },
      immediate: true,
    },
    role() {
      this.form.role = this.role;
    },
  },
  created() {
    this.sys_user_add = this.permissions["sys_user_add"];
    this.sys_user_edit = this.permissions["sys_user_edit"];
    this.sys_user_del = this.permissions["sys_user_del"];
    this.init();
  },
  methods: {
    init() {
      fetchTree().then((response) => {
        this.treeData = response.data.data;
      });
      getTreeList().then((response) => {
        this.treeListData = response.data.data;
      });
      remoteDict("user_zj").then((response) => {
        this.userZjOptions = response.data.data;
      });
    },
    editHead(userId) {
      this.$refs.headForm.init(userId);
    },
    nodeClick(data) {
      this.searchForm = {};
      this.page.page = 1;
      this.getList(this.page, {
        deptId: data.id,
      });
    },
    getList(page, params) {
      this.listLoading = true;
      fetchList(
        Object.assign(
          {
            current: page.currentPage,
            size: page.pageSize,
          },
          params,
          this.searchForm,
          this.zdySearchForm
        )
      ).then((response) => {
        this.list = response.data.data.records;
        this.page.total = response.data.data.total;
        this.listLoading = false;
      });
    },
    getNodeData() {
      deptRoleList().then((response) => {
        let data = response.data.data;
        if (this.userInfo.username != "admin") {
          for (var i in data) {
            if (data[i].roleCode == "ROLE_ADMIN") {
              data[i].disabled = true;
            }
          }
        }
        this.rolesOptions = data;
      });
    },
    searchChange(param, done) {
      this.searchForm = param;
      this.page.currentPage = 1;
      this.getList(this.page, param);
      done();
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    currentChange(current) {
      this.page.currentPage = current;
    },
    refreshChange() {
      this.getList(this.page);
    },
    handleOpenBefore(show, type) {
      window.boxType = type;
      // 查询部门树
      fetchTree().then((response) => {
        this.treeDeptData = response.data.data;
      });
      // 查询角色列表
      deptRoleList().then((response) => {
        let data = response.data.data;
        if (this.userInfo.username != "admin") {
          for (var i in data) {
            if (data[i].roleCode == "ROLE_ADMIN") {
              data[i].disabled = true;
            }
          }
        }
        this.rolesOptions = data;
      });

      if (["edit", "views"].includes(type)) {
        this.role = [];
        for (let i = 0; i < this.form.roleList.length; i++) {
          this.role[i] = this.form.roleList[i].roleId;
        }
      } else if (type === "add") {
        this.role = [];
        this.form.username = undefined;
        this.form.ryName = undefined;
        this.form.phone = undefined;
        this.form.password = undefined;
        //性别
        this.form.ryXb = undefined;
        // 职级
        this.form.ryZjbm = undefined;
        //部门
        this.form.deptId = undefined;
        // 状态
        this.form.lockFlag = undefined;
        //职位
        this.form.ryZw = undefined;
        //身份
        this.form.ryCpsf = undefined;
        //签名
        this.form.ryQmtp = undefined;
      }
      show();
    },
    handleUpdate(row, index) {
      this.$refs.crud.rowEdit(row, index);
      this.form.password = undefined;
    },
    //图片上传
    handleAvatarSuccess(res, file) {
      this.form.avatar = res.data.url;
    },
    handleAvatarSuccessQm(res, file) {
      this.form.ryQmtp = res.data.url;
    },
    create(row, done, loading) {
      if (!this.form.password) {
        this.$notify.closeAll();
        this.$notify.error("请填写密码");
        loading();
        return;
      }
      if (this.form.phone && this.form.phone.indexOf("*") > 0) {
        this.form.phone = undefined;
      }
      addObj(this.form)
        .then(() => {
          this.getList(this.page);
          done();
          this.$notify.closeAll();
          this.$notify.success("创建成功");
          this.$emit("addUpdateOk");
        })
        .catch(() => {
          loading();
        });
    },
    getDeptDetail(param1, param2) {
      let lResult = "";

      for (let i = 0; i < this.treeListData.length; i++) {
        if (this.treeListData[i].deptId == param1) {
          lResult =
            param2 === "code"
              ? this.treeListData[i].deptCode
              : this.treeListData[i].deptName;
          break;
        }
      }
      return lResult;
    },
    update(row, index, done, loading) {
      if (this.form.phone && this.form.phone.indexOf("*") > 0) {
        this.form.phone = undefined;
      }

      this.form.deptCode = this.getDeptDetail(this.form.deptId, "code");
      this.form.deptName = this.getDeptDetail(this.form.deptId, "name");
      this.form.orgaCode = this.getDeptDetail(this.form.orgaId, "code");
      this.form.orgaName = this.getDeptDetail(this.form.orgaId, "name");
      putObj(this.form)
        .then(() => {
          this.getList(this.page);
          done();
          this.$notify.closeAll();
          this.$notify.success("修改成功");
          this.$emit("addUpdateOk");
        })
        .catch(() => {
          loading();
        });
    },
    deletes(row, index) {
      this.$confirm(
        "此操作将永久删除该用户(用户名:" + row.username + "), 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        delObj(row.userId)
          .then(() => {
            this.list.splice(index, 1);
            this.$notify.closeAll();
            this.$notify.success("删除成功");
          })
          .catch(() => {
            this.$notify.closeAll();
            this.$notify.error("删除失败");
          });
      });
    },
    getArray(strArr, type) {
      if (strArr) {
        return strArr.split(type ? type : ",");
      } else {
        return [];
      }
    },
  },
};
</script>
<style lang="scss">
.user {
  height: 100%;

  &__tree {
    padding-top: 3px;
    padding-right: 20px;
  }

  &__main {
    .el-card__body {
      padding-top: 0;
    }
  }
}
</style>
